//小程序订阅通知
export const state = {
    subscribeMessageIdsMap: [], //小程序订阅消息模板ids
};

export const getters = {
    subscribeMessageIdsMap: (state) => state.subscribeMessageIdsMap,
};
export const actions = {
    async getMessageIds({commit}) {
        const {data} = await uni.$u.http.post("user/getNotices");
        commit("formatMessage", data);
        return data;
    },
};
export const mutations = {
    formatMessage(state, messageIdsObj) {
        const typeMap = {
            order: ["order_payed", "order_finish"],
            money: ["money_change","withdraw_change"],
            refund: ["refund_back", "refund_success"],
            commission:["become_agent","commission_money"]
        };
        const idsMap = {};
        Object.keys(typeMap).forEach((key) => {
            idsMap[key] = [];
            typeMap[key].forEach((item) => {
                if(!uni.$u.test.isEmpty(messageIdsObj[item])){
                    idsMap[key].push(messageIdsObj[item]);
                }
            });
        });
        

        state.subscribeMessageIdsMap = idsMap;
    },
    subScribeMsg(state,typeArr) {
        return new Promise((resolve, reject) => {
            let tmplIds = [];
            typeArr.forEach(function (v) {
                if(!uni.$u.test.isEmpty(state.subscribeMessageIdsMap[v])){
                    tmplIds = tmplIds.concat(state.subscribeMessageIdsMap[v]);
                }
            });
            if(!uni.$u.test.isEmpty(tmplIds)){
                uni.getSetting({
                    withSubscriptions: true,
                    success(res) {
                        if (!res.subscriptionsSetting.mainSwitch) {
                            uni.openSetting({
                                success(res) {
                                    console.log('打开设置页', res.authSetting);
                                }
                            })
                        } else {
                            uni.requestSubscribeMessage({
                                tmplIds: tmplIds,
                                success(res) {
                                    resolve(res)
                                },
                                fail(errMessage) {
                                    reject(errMessage)
                                },
                                complete(res) {
                                    console.log('订阅结果', res);
                                }
                            });
                        }
                    }
                });
            }else{
                resolve();
            }
        });
    }
};
